import os
import subprocess
import sys
import time
from configparser import ConfigParser

"""
[cwd]
repertoryPath = D:\***\***

[git]
remotePepertory = ***
ssh = ***

"""

def main():
    cf = ConfigParser()
    cf.read('config')

    # change working directory
    os.chdir(cf.get('cwd', 'repertoryPath'))

    # check if git init
    if '.git' not in os.listdir():
        subprocess.check_call(['git', 'init'])

    # check if remote in config, if not, add the remote
    git_remotes = subprocess.check_output(['git', 'remote', '-v'])
    git_remotes_str = bytes.decode(git_remotes).strip()
    git_remotes_list = [line.split()[0] for line in git_remotes_str.split('\n')]
    if cf.get('git', 'remotePepertory') not in git_remotes_list:
        subprocess.check_call(['git', 'remote', 'add', k, v[0]])

    # pull & merge
    subprocess.check_call(['git', 'pull'])
    subprocess.check_call(['git', 'merge'])

    # add . & commit with message
    subprocess.check_call(['git', 'add', '.'])
    commit_message = ' commit code ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if len(sys.argv) == 2:
        commit_message = sys.argv[1] + commit_message
    subprocess.call(['git', 'commit', '-m', commit_message])

    # push to every remote repo
    subprocess.check_call(['git', 'push', cf.get('git', 'remotePepertory'), 'master'])


if __name__ == '__main__':
    if len(sys.argv) == 2:
        if sys.argv[1] == '-h':
            print('Usage:\n\t%s [commit_message]' %sys.argv[0])
    main()